import { NextRequest, NextResponse } from 'next/server';
import SmsService, { VerificationPurpose } from '@/utils/smsService';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { phone, code, purpose } = body;
    
    console.log(`尝试验证码: ${code}, 手机号: ${phone}, 用途: ${purpose}`);
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone || !phoneRegex.test(phone)) {
      console.log('验证失败: 手机号格式不正确');
      return NextResponse.json(
        { error: '手机号格式不正确' },
        { status: 400 }
      );
    }
    
    // 验证验证码格式
    if (!code || !/^\d{6}$/.test(code)) {
      console.log('验证失败: 验证码格式不正确');
      return NextResponse.json(
        { error: '验证码格式不正确' },
        { status: 400 }
      );
    }
    
    // 验证用途
    if (!purpose || !['registration', 'password_reset'].includes(purpose)) {
      console.log('验证失败: 无效的验证码用途');
      return NextResponse.json(
        { error: '无效的验证码用途' },
        { status: 400 }
      );
    }
    
    // 验证验证码
    const isValid = await SmsService.verifyCode(
      phone, 
      code, 
      purpose as VerificationPurpose
    );
    
    if (isValid) {
      console.log(`验证码验证成功: ${phone}`);
      return NextResponse.json({
        success: true,
        message: '验证码验证成功'
      });
    } else {
      console.log(`验证码验证失败: ${phone}`);
      return NextResponse.json(
        { 
          success: false,
          error: '验证码无效或已过期' 
        },
        { status: 400 }
      );
    }
  } catch (error) {
    console.error('验证码验证过程中发生错误:', error);
    return NextResponse.json(
      { 
        success: false,
        error: '服务器错误，请稍后再试' 
      },
      { status: 500 }
    );
  }
}
